<template>
  <div class="printhome">
    <div v-if="state.printDivShow">
      <el-button type="primary" v-print="printOjb">打印</el-button>
      <el-button type="primary" @click="downloadImg">下载图片</el-button>
      <el-button type="primary" @click="downloadPdf">下载pdf</el-button>
    </div>
    <img v-if="state.capturedImage" :src="state.capturedImage" alt="转换后的图片"/>
    <div id="printdiv" class="clearfix" ref="printdiv">
      <table class="ptable">
        <tr v-for="(item,index) in state.trCount" :key="index" >
          <td>
            <PrintItem :autoid="state.autoIds[index*2]" :inx="index*2" v-if="props.typeId===1" ></PrintItem>
          </td>
          <td>
            <PrintItem :autoid="state.autoIds[index*2+1]" :inx="index*2+1" v-if="index*2+1 < state.autoIds.length && props.typeId===1"></PrintItem>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script setup name="printHomeIndex">
import {reactive, ref, onMounted, onUnmounted, defineProps, defineEmits, nextTick, defineAsyncComponent} from "vue";
import request from "/@/utils/request";
import {ElMessage} from "element-plus";
import html2canvas from 'html2canvas'
import jsPDF from "jspdf";
import other from '/@/utils/other';

const PrintItem = defineAsyncComponent(() => import('/@/views/kucun/cs/printitem.vue'));

// 定义父组件传过来的值
const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  autoIds: {
    type: Array,
    default: () => [],
  },
  typeId:{
    type:Number,
    default:1
  }
});
const printdiv = ref(null)

const state = reactive({
  autoIds : [],
  trCount:0,
  printDivShow : false,
  capturedImage : ''
})
const addprintcount = ()=>{
  request({
    url: '/currentstore/addprintcount',
    data: {ids : props.autoIds}
  }).then(res => {
    if(res.code !== '200'){
      ElMessage.error(e.msg)
    }
  })
}
const printOjb = ref({
  id: "printdiv", // 这里是要打印元素的ID
  title : '二维码打印',
  zIndex:20003,
  openCallback(vue){
    addprintcount();
  }
})
// const downloadImg = ()=>{
//   html2canvas(document.querySelector('#printdiv'), {useCORS: true}).then((canvas) => {
//     state.capturedImage = canvas.toDataURL('image/png');
//   })
// }
const downloadImg = () => {
  // 设置height和windowwHeight属性，防止只下载当前看到的页面，这样就可以下载完整的内容
  const containerElement = document.querySelector('#printdiv')
  html2canvas(containerElement, {
    allowTaint: true,
    useCORS: true,
    scale: 1,
    height: containerElement.scrollHeight,
    windowHeight: containerElement.scrollHeight
  }).then(canvas => {
    canvas.toBlob(blob => {
      const href = window.URL.createObjectURL(new Blob([blob]))
      const link = document.createElement('a')
      link.href = href
      link.download = other.uuid() + '.png'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }, 'image/png')
    addprintcount();
  })
}
const downloadPdf = ()=>{
  html2canvas(document.querySelector("#printdiv"), {
    allowTaint: true,
    useCORS: true,
    scale: 1
  }).then(function(canvas) {
    let contentWidth = canvas.width;
    let contentHeight = canvas.height;
    let pageHeight = (contentWidth / 592.28) * 841.89;
    let leftHeight = contentHeight;
    let position = 0;
    let imgWidth = 595.28;
    let imgHeight = (592.28 / contentWidth) * contentHeight;
    let pageData = canvas.toDataURL("image/jpeg", 1.0);
    let PDF = new jsPDF("", "pt", "a4");
    if (leftHeight < pageHeight) {
      PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
    } else {
      while (leftHeight > 0) {
        PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
        leftHeight -= pageHeight;
        position -= 841.89;
        if (leftHeight > 0) {
          PDF.addPage();
        }
      }
    }
    PDF.save(other.uuid() + ".pdf");
    addprintcount();
  });
}
onMounted(()=>{
  state.autoIds = props.autoIds
  state.trCount = Math.ceil(state.autoIds.length / 2)
  nextTick(()=>{
    setTimeout(()=>{
      state.printDivShow = true
    },state.autoIds.length*20)
  })
})
</script>

<style scoped lang="scss">
@media print {
  .printhome {
    width: 100%; /* 确保内容宽度为100% */
    margin: 0;   /* 移除默认的边距 */
    padding: 10px; /* 根据需要设置内边距 */
  }
  #printdiv {
    width: 100%; /* 确保内容宽度为100% */
    margin: 0;   /* 移除默认的边距 */
    padding: 10px; /* 根据需要设置内边距 */
  }
}
.printhome{
  width: 100%;
  #printdiv{
    width: 100%;
  }
  .ptable{
    td{
      width: 340px;
    }
  }
}
</style>
